package xyz.ieden.hello.advice;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import xyz.ieden.commons.constant.GlobalConstant;
import xyz.ieden.commons.entity.RetInfo;
import xyz.ieden.commons.exception.ValidateException;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Gavin on 2017.08.05.
 * 全局异常建言
 */
@ControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 数据验证异常的管理
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = {ValidateException.class})
    public RetInfo<Object> validateExceptionHandler(HttpServletRequest request, Exception e) {
        System.out.println("访问URL：" + request.getRequestURL());
        System.out.println("异常信息：" + e.getMessage());
        RetInfo<Object> retInfo = new RetInfo<>();
        retInfo.setResult(GlobalConstant.RESULT_SUCCESS_CODE);
        retInfo.setRetCode(GlobalConstant.RET_PARAM_ERROR_CODE);
        retInfo.setRetMsg("Param ");
        return retInfo;
    }

    /**
     * 运行时异常的管理
     *
     * @param request
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = {RuntimeException.class})
    public ModelAndView runtimeExceptionHandler(HttpServletRequest request, Exception e) {
        System.out.println("访问URL：" + request.getRequestURL());
        System.out.println("异常信息：" + e.getMessage());
        ModelAndView modelAndView = new ModelAndView("/error.html");
        modelAndView.addObject("retInfo", "");
        return modelAndView;
    }


    /**
     * 默认的异常管理
     *
     * @param request
     * @param e
     */
    @ExceptionHandler(value = {Exception.class})
    public void defaultExceptionHandler(HttpServletRequest request, Exception e) {
        System.out.println("访问URL：" + request.getRequestURL());
        System.out.println("异常信息：" + e.getMessage());
        e.printStackTrace();
    }
}
